package main

import (
	"fmt"
	"github.com/0xe2-0x9a-0x9b/Go-SDL/sdl"
	"github.com/0xe2-0x9a-0x9b/Go-SDL/ttf"
	"math/rand"
	"strconv"
	"time"
)

func loadImage(name string) *sdl.Surface {
	image := sdl.Load(name)

	if image == nil {
		panic(sdl.GetError())
	}

	return image

}

func main() {
	if sdl.Init(sdl.INIT_VIDEO) != 0 {
		panic(sdl.GetError())
	}
	if ttf.Init() != 0 {
		panic(sdl.GetError())
	}
	defer ttf.Quit()
	// On Linux machines, /etc/fonts/fonts.conf should contain the list of font locations
	// may default to /usr/share/fonts (./truetype for the fonts we want)
	// parsing /etc/fonts/fonts.conf needs xml (or look for the <dir> blocks containing locations
	// /usr/share/fonts/truetype/freefont/FreeMono.ttf should be present everywhere??
	defer sdl.Quit()

	screen := sdl.SetVideoMode(400, 300, 32, 0)
	if screen == nil {
		panic(sdl.GetError())
	}

	font := ttf.OpenFont("/usr/share/fonts/truetype/freefont/FreeMono.ttf", 60)
	if font == nil {
		panic(sdl.GetError())
	}
	h := int16(font.Height())
	defer font.Close()
	white := sdl.Color{255,255,255,0}

	//make a map of characters to surfaces containing their rendering
	textmap := make(map[rune]*sdl.Surface)
	//for i:=65; i<91; i++ {	//Latin chars
	for i:=0x391; i<0x39F; i++ { //Greek chars
		textmap[rune(i)] = ttf.RenderUTF8_Solid(font, string(rune(i)), white) 
		fmt.Printf("%i %c\n", i, i)
		if textmap[rune(i)] == nil {
			panic("Issue with " + string(rune(i)) + "," + string(i))
		}
	}
	unistr := "ΑΝΞΔΖ";
	sdl.WM_SetCaption("Template", "")

	ticker := time.NewTicker(1e9 / 2 /*2 Hz*/ )

loop:
	for {
		select {
		case <-ticker.C:
			// Note: For better efficiency, use UpdateRects instead of Flip
			screen.FillRect(nil, /*color*/ rand.Uint32())
		//	r := rune(rand.Intn(10)+0x391)
			r := rune(' ')
			workingstr := unistr //decode the input UTF8 string
			pos := int16(0)
			for i:=0; len(workingstr) > 0; i,pos=i+1,pos+h {
				r, _, workingstr, _ = strconv.UnquoteChar(workingstr,0)  
				screen.Blit(&sdl.Rect{pos+h,h,uint16(pos),0}, textmap[r], nil)
			}
			//screen.Blit(&sdl.Rect{x,y, 0, 0}, image, nil)
			screen.Flip()

		case event := <-sdl.Events:
			fmt.Printf("%#v\n", event)

			switch event.(type) {
			case sdl.QuitEvent:
				break loop
			}
		}
	}
}
